package pers.xhh.frontapi.service.impl;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.xhh.frontapi.common.ResultCode;
import pers.xhh.frontapi.config.AlipayTemplate;
import pers.xhh.frontapi.entity.*;
import pers.xhh.frontapi.entity.vo.pay.PayAsyncVo;
import pers.xhh.frontapi.entity.vo.pay.PayOrderVo;
import pers.xhh.frontapi.entity.vo.pay.PayVo;
import pers.xhh.frontapi.enume.OrderStatusEnum;
import pers.xhh.frontapi.service.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author wei-xhh
 * @date 2020-12-10
 */
@Service
public class PayServiceImpl implements PayService {

    @Autowired
    AlipayTemplate alipayTemplate;

    @Autowired
    MiOrderService miOrderService;

    @Autowired
    MiWareService miWareService;

    @Autowired
    MiPaymentInfoService miPaymentInfoService;

    @Autowired
    MiOrderItemService miOrderItemService;

    @Autowired
    MiGoodsService miGoodsService;

    @Override
    public String payOrder(PayOrderVo payOrderVo) throws AlipayApiException {

        // TODO 确认订单号，价格是否正确
        String orderSn = payOrderVo.getOrderSn();
        String payPrice = payOrderVo.getPayPrice();
        MiOrderEntity miOrderEntity =
                miOrderService.getOne(new QueryWrapper<MiOrderEntity>().eq("order_sn", orderSn));
        if(miOrderEntity == null){
            return ResultCode.ERROR1202.getMessage();
        } else {
            BigDecimal payAmount = miOrderEntity.getPayAmount();
            String s = payAmount.toString();
            if(!s.equals(payPrice)){
                return ResultCode.ERROR1203.getMessage();
            }
        }

        // ->发起支付
        PayVo payVo = new PayVo();
        // 生成支付宝订单号
//        String idStr = "zfb_" + IdWorker.getIdStr();
        // 保存订单号
//        MiOrderEntity miOrderEntity = miOrderService.
//                getOne(new QueryWrapper<MiOrderEntity>().eq("order_sn", payOrderVo.getOrderSn()));
//        if(miOrderEntity != null){
//            miOrderEntity.setTradeNo(idStr);
//        }
//        miOrderService.updateById(miOrderEntity);

        // ->发起支付
        payVo.setOut_trade_no(payOrderVo.getOrderSn());
        payVo.setSubject(payOrderVo.getOrderSn());
        payVo.setTotal_amount(payOrderVo.getPayPrice());
        if(payOrderVo.getBody() != null){
            payVo.setBody(payOrderVo.getBody());
        }
        String pay = alipayTemplate.pay(payVo);
        return pay;
    }

    @Override
    public boolean success() {
        // 1.更新库存
//        miWareService.getOne();
        return false;
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        MiPaymentInfoEntity infoEntity = new MiPaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(new Date());

        miPaymentInfoService.save(infoEntity);

        //2、修改订单的状态信息
        if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            // 支付成功状态
            String outTradeNo = vo.getOut_trade_no();
            boolean b = miOrderService.updateOrderStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());

            // 更新商品数量,mi_ware表,goods表
            List<MiOrderItemEntity> orderItemEntities =
                    miOrderItemService.list(new QueryWrapper<MiOrderItemEntity>().eq("order_sn", outTradeNo));
            for (MiOrderItemEntity orderItemEntity : orderItemEntities) {
                Integer goodsId = orderItemEntity.getGoodsId();
                // ->更新

                MiGoodsEntity miGoodsEntity = miGoodsService.getById(goodsId);
                if(miGoodsEntity != null){
                    Integer goodsNumber = miGoodsEntity.getGoodsNumber();
                    Integer newNumber = goodsNumber - orderItemEntity.getCount();
                    miGoodsEntity.setGoodsNumber(newNumber);
                    miGoodsService.updateById(miGoodsEntity);
                }

                MiWareEntity miWareEntity = miWareService.getOne(new QueryWrapper<MiWareEntity>().eq("goods_id", goodsId));
                if(miWareEntity != null){
                    Integer stock = miWareEntity.getStock();
                    Integer stockLocked = miWareEntity.getStockLocked();
                    Integer newStock = stock - orderItemEntity.getCount();
                    if(newStock > 0){
                        miWareEntity.setStock(newStock);
                    } else {
                        miWareEntity.setStock(0);
                    }
                    if((stockLocked - orderItemEntity.getCount()) > 0){
                        miWareEntity.setStockLocked(stockLocked - orderItemEntity.getCount());
                    } else {
                        miWareEntity.setStockLocked(0);
                    }
                    miWareService.updateById(miWareEntity);
                }
            }
        }
        return "success";
    }
}
